package fr.licpro.filebox.service.sync;

import android.content.Intent;
import android.os.Parcel;
import android.os.Parcelable;
import retrofit.RetrofitError;
import fr.licpro.filebox.dto.response.TokenDto;
import fr.licpro.filebox.service.IRestClient;


/**
 * Class to Sync the startUp data
 * @author Abdessamad EL FATTAKE
 * @author Sylvain LE GOUELLEC
 * @since 1.0.0
 */
public class ConnectionSync extends AbstractSync<TokenDto> implements Parcelable{

	/**
	 * Constant used to know when the connection to the server is done
	 */
	public static final String CONNECTION_DONE = "CONNECTION_DONE";
	
	/**
	 * User's login
	 */
	private String mLogin;
	
	/**
	 * User's password
	 */
	private String mPassword;

	/**
	 * Complete constructor of ConnectionSync's class
	 * @param login
	 * @param password
	 */
	public ConnectionSync(String login, String password)
	{
		this.mLogin = login;
		this.mPassword = password;
	}
	
	@Override
	protected TokenDto execute(final IRestClient pRestClient) throws RetrofitError 
	{
		TokenDto tDtao = pRestClient.getToken(mLogin, mPassword);
		return tDtao;
	}

	@Override
	protected void onSuccess() 
	{
		Intent i = new Intent(ConnectionSync.CONNECTION_DONE);
		i.putExtra(ConnectionSync.CONNECTION_DONE, ((TokenDto)mData).getToken());
		i.setPackage("fr.licpro.filebox");
		mContext.sendBroadcast(i);
	}

	@Override
	protected void onError(Exception e) 
	{
	}

	@Override
	public int describeContents() 
	{
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) 
	{
		dest.writeString(mLogin);
		dest.writeString(mPassword);
	}

	public static final Parcelable.Creator<ConnectionSync> CREATOR = new Parcelable.Creator<ConnectionSync>() {
		public ConnectionSync createFromParcel(Parcel in) {
		    return new ConnectionSync(in);
		}
		
		public ConnectionSync[] newArray(int size) {
		    return new ConnectionSync[size];
		}
    };
    
    /**
     * Constructor for Parcelable implementation
     * @param in 	Instance of object serialized
     */
    public ConnectionSync(Parcel in) 
    {
    	mLogin = in.readString();
    	mPassword = in.readString();
	}
}
